package com.mtiiot.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.mtiiot.proto.Data;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * 基本常量,配置文件定义
 *
 * @author 卢承业
 */
public class Constants {
    //public static InstruProducer ip = new InstruProducer();
    private static LogService1 logService1;
    private static RedisService1 redisService1;
    // 2016.09。14 ，加kafka和netty服务
    private static KafkaMqService1 kafkaMqService1;
    private static NettyService1 nettyService1;
    private static RedisMqService1 redisMqService1;

    private static Logger logger = LogManager.getLogger(Constants.class);
    public static final String key = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4";//秘钥
    public static final byte[] keyiv = {1, 2, 3, 4, 5, 6, 7, 8};//iv
    public static Config config;
    //public static int port;//服务器端口
    public static String configPath;

    //**************************常量定义*********************************
    public static final String MESSAGEQUEUE = "messageQueue";//
    public static final String MESSAGEALl = "all";//
    public static final String BEANTYPE_COMMON = "Common";//
    public static final String REQ_TYPE_Y = "Y";//同步请求
    public static final String REQ_TYPE_N = "N";//异步请求

    // 2016-07-29:InstrumentPassword_(以前)
    public static final String INSPWD_PFEFIX = "PARAM_DEVICE_PASSWORD_";//仪器密码前缀

    public static final String EXCEPRION_TYPE_CODETYPEERROR = "code 类型错误,系统无法识别!";//异步请求
    public static final String EXCEPRION_TYPE_VALIDEFAILURE = "data 验证失败!";//异步请求
    public static final String EXCEPRION_TYPE_PRPTOERRPR = "proto 格式异常!";//异步请求
    //**************************常量定义*********************************

    //**************************日志常量定义*********************************
    public static final String LOGCONTENT_MESSAGE = "ok";//
    public static final String LOGLEVEL_ERROR = "error";//
    public static final String LOGLEVEL_WARNING = "warning";//
    public static final String LOGTYPE_ERROR = "error";
    public static final String LOGTYPE_PROCESS = "process";
    public static final String LOGTYPE_REQUEST = "request";
    public static final String LOGTYPE_SERVERHEART = "serverHeart";

    //**************************日志常量定义*********************************

    //**************************服务状态定义*********************************
    public static final String SERVERSTATUS_START = "start";
    public static final String SERVERSTATUS_RUNNING = "running";
    public static final String SERVERSTATUS_END = "end";
    //**************************服务状态定义*********************************

    //	private static final String NAME = "config.properties";
    private static final String LOG4J = "log4j.properties";

    // 仪器盒子异常信息code
    public static final String N_BX_ERR_MESG = "N_BX_ERR_MESG";
    public static final String N_IS_ERR_MESG = "N_IS_ERR_MESG";
    public static final String N_BX_STA_HSZZ = "N_BX_STA_HSZZ";

    /*
    * 获取客户端的IP
    * */
    public static  String CLIENT_HOST_IP = "";
    /*
    * 获取客户端的名字
    * */
    public static String CLIENT_HOST_NAME = "";

    /**
     * 初始化
     */
    public static void init() {
        initConfig();//配置文件初始化
        //initLog4j();//日志文件初始化
    }

    /**
     * 初始化平台服务
     */
    public static void initFsServer() {
        try {
            //ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:/applicationContext-netty.xml");
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("file:" + Constants.config.getApplicationPath());
            logService1 = (LogService1) context.getBean("logService", LogService1.class);
            redisService1 = (RedisService1) context.getBean("redisService", RedisService1.class);
            // 调用消息队列的服务
            kafkaMqService1 = (KafkaMqService1) context.getBean("kafkaMqService", KafkaMqService1.class);
            // 调用netty的服务
            nettyService1 = (NettyService1) context.getBean("nettyService", NettyService1.class);
            // 调用redis消息队列服务
            redisMqService1 = (RedisMqService1) context.getBean("redisMqService",RedisMqService1.class);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 获取日志服务
     *
     * @return
     */
    public static LogService1 getLogService() {
        try {
            if (logService1 != null) {
                return logService1;
            }
            initFsServer();
            return logService1;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获取redis 服务
     *
     * @return
     */
    public static RedisService1 getRedisService() {
        try {
            if (redisService1 != null) {
                return redisService1;
            }
            initFsServer();
            return redisService1;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获取kafka的消息队列 服务
     *
     * @return
     */
    public static KafkaMqService1 getKafkaMqService() {
        try {
            if (kafkaMqService1 != null) {
                return kafkaMqService1;
            }
            initFsServer();
            return kafkaMqService1;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获取kafka的消息队列 服务
     *
     * @return
     */
    public static NettyService1 getNettyService() {
        try {
            if (nettyService1 != null) {
                return nettyService1;
            }
            initFsServer();
            return nettyService1;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }
    /**
     * 获取redis的消息队列 服务
     *
     * @return
     */
    public static RedisMqService1 getRedisMqService() {
        try {
            if (redisMqService1 != null) {
                return redisMqService1;
            }
            initFsServer();
            return redisMqService1;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }


    /**
     * 初始化配置
     * */
    public static void initConfig() {
        Properties properties = new Properties();
        try {
            InputStream inputStream = new FileInputStream(configPath);
            properties.load(inputStream);
            inputStream.close(); //关闭流  
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        Config config = new Config();
        config.setLogConfigPath(properties.getProperty("logConfigPath"));
        config.setApplicationPath(properties.getProperty("applicationPath"));
        config.setServerPort(Integer.parseInt(properties.getProperty("serverPort")));
        config.setBacklog(Integer.parseInt(properties.getProperty("backlog")));
        config.setPath(properties.getProperty("path"));
        config.setSeparator(properties.getProperty("separator"));
        config.setAllIdleTime(Long.parseLong(properties.getProperty("allIdleTime")));
        config.setMsgMaxlenth(Integer.parseInt(properties.getProperty("msgMaxlenth")));
        config.setMsgHandleType(properties.getProperty("msgHandleType"));
        config.setLogIntoSys(Boolean.valueOf(properties.getProperty("logIntoSys")));
        config.setGetPwdFromRedis(Boolean.valueOf(properties.getProperty("getPwdFromRedis")));
        config.setServerIp(properties.getProperty("serverIp"));
        config.setServerHeartTime(Long.parseLong(properties.getProperty("serverHeartTime")) * 1000);
        /** 指定数据进那个消息队列*/
        config.setMqServer(properties.getProperty("mqServer"));
        /** 验证元数据的系统ID*/
        config.setSysId(properties.getProperty("sysId"));
        config.setBoxSysId(properties.getProperty("boxSysId"));
        config.setTestCode(properties.getProperty("testCode"));
        config.setTestDataPath(properties.getProperty("testDataPath"));

        Map<String, String> map = new HashMap<String, String>();
        map.put("2ede249e89bb4f1aaa7e3e60d5d4fb15", "3c72f831bb4f4abc9a88670193263e4d");
        map.put("2ede249e89bb4f1aaa7e3e60d5d4fb14", "3c72f831bb4f4abc9a88670193263e4e");
        map.put("6a0caa9e836b487aa6aeabe371ba3051", "3c72f831bb4f4abc9a88670193263e4d");
        map.put("4af4e88a53c8174f0153ea9ca10b497a", "3c72f831bb4f4abc2188656193263e4d");
        map.put("c630fa17905f4e4889cce61130ebace6", "c669a33e9485365dc9c6a6f4bf03eea9");
        map.put("a03ee176a48f4004a8abe093badcf0be", "a0a09347ea455489c62b34ecd2722c85");
        map.put("c77f159bce8c4d92ab075798c6685add", "a0a09347ea455489c62b34ecd2722c85");
        map.put("8ff1e43ebdd64b12a7d2a68ff55daed3", "e59edfbfc4e15b6cbc4af29926bfb832");
        map.put("6e97fa1840954e1b8783b5b072565770", "65c8d04231a93a848a4f1b3fa8d3e033");
        map.put("26e7a916547a4d91b146a4f29d41b0ac", "c7364ec1e2658550cc0f2166298562b0");
        config.setIns(map);
        Constants.config = config;
    }

    public static void initLog4j() {
//		Properties props = new Properties();
//		try {
//			InputStream inputStream = Constants.class.getClassLoader()
//					.getResourceAsStream(LOG4J);
//			props.load(inputStream);
//			inputStream.close(); // 关闭流
//			String sysName=System.getProperties().getProperty("os.name");
//			String path="";
//			if(sysName.indexOf("Windows")!=-1){
//				path=System.getProperty("mapper.dir")+"\\";
//			}else{
//				path=Utils.getCurrentRunableJarPath();
//			}
//			String proFile=props.getProperty("file");
//			String filePath=path+"log_"+Constants.port+"/"+proFile;
//			props.setProperty("log4j.appender.LisMac.File", filePath);
//			PropertyConfigurator.configure(props);
//		} catch (IOException e) {
//			logger.error("log config init exception:"+e.getMessage());
//		}
    }

    /*
    * 将group转成json
    * */
    public static String groupToString(Data.Group group){
        StringBuilder sb = new StringBuilder();
        sb.append("id=").append(group.getId()).append("\r\n");
        sb.append("time=").append(group.getTime()).append("\r\n");
        sb.append("dynamicPwd=").append(group.getDynamicPwd()).append("\r\n");
        sb.append("code=").append(group.getCode()).append("\r\n");
        sb.append("error=").append(group.getError()).append("\r\n");
        sb.append("seqNo=").append(group.getSeqNo()).append("\r\n");
        sb.append("body=").append(group.getBody());
        return sb.toString();
    }

}

	
